package com.myapp.api.controller;

import com.myapp.api.entity.Admin;
import com.myapp.api.entity.Student;
import com.myapp.api.entity.Teacher;
import com.myapp.api.other_param.LoginForm;
import com.myapp.api.service.AdminService;
import com.myapp.api.service.StudentService;
import com.myapp.api.service.TeacherService;
import com.myapp.api.tools.*;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;

@Api(value = "LoginController",description = "登录获取 jwt token 操作")
@RestController
@RequestMapping(value = "/login", produces = "application/json;charset=UTF-8")
public class LoginController {
    @Autowired
    private AdminService service1;
    @Autowired
    private StudentService service2;
    @Autowired
    private TeacherService service3;

    // 默认过期时间是 1 天
    private static final long EXPIRATION = 3600L * 24;
    // 选择了记住我之后的过期时间为 7 天
    private static final long EXPIRATION_REMEMBER = 3600L * 24 * 7;

    @PostMapping
    public ResponseEntity<?> login(@Valid @RequestBody LoginForm record, HttpServletRequest request, BindingResult bindingResult) {
        String account = record.getAccount();
        String pwd = record.getPwd();
        String role = record.getRole();
        boolean rememberMe = record.isRememberMe();
        long expiration = rememberMe ? EXPIRATION_REMEMBER : EXPIRATION;

        if (bindingResult.hasErrors()) {
            HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
            JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, bindingResult.getFieldError().getDefaultMessage());
            return new ResponseEntity<JsonResult>(result, status);
        } else {
            if (role.equals("ADMIN")) {
                Admin admin = service1.getAdminByAccount(account);
                if (admin != null) {
                    pwd = MD5Utils.encode(pwd);
                    if (admin.getPwd().equals(pwd)) {
                        String token = JWTUtils.createToken(account, admin.getUsername(), role, rememberMe);
                        AccessToken accessToken = new AccessToken(token, "Bearer", role, expiration);
                        admin.setAuthtoken(token.replace(JWTUtils.TOKEN_PREFIX,""));
                        admin.setLoginip(IPUtils.getIpAdr(request));
                        admin.setLogintime(new Date());
                        admin.setUpdatetime(new Date());
                        service1.putAdmin(admin);
                        HttpStatus status = HttpStatus.OK;
                        return new ResponseEntity<AccessToken>(accessToken, status);
                    } else {
                        HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
                        JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, "账号密码错误");
                        return new ResponseEntity<JsonResult>(result, status);
                    }
                } else {
                    HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
                    JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, "不存在的账号：" + account);
                    return new ResponseEntity<JsonResult>(result, status);
                }
            } else if (role.equals("STUDENT")) {
                Student student = service2.getStudentBySid(account);
                if (student != null) {
                    pwd = MD5Utils.encode(pwd);
                    if (student.getPwd().equals(pwd)) {
                        String token = JWTUtils.createToken(account, student.getSname(), role, rememberMe);
                        AccessToken accessToken = new AccessToken(token, "Bearer", role, expiration);
                        student.setAuthtoken(token.replace(JWTUtils.TOKEN_PREFIX, ""));
                        student.setLoginip(IPUtils.getIpAdr(request));
                        student.setLogintime(new Date());
                        student.setUpdatetime(new Date());
                        service2.putStudent(student);
                        HttpStatus status = HttpStatus.OK;
                        return new ResponseEntity<AccessToken>(accessToken, status);
                    } else {
                        HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
                        JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, "账号密码错误");
                        return new ResponseEntity<JsonResult>(result, status);
                    }
                } else {
                    HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
                    JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, "不存在的账号：" + account);
                    return new ResponseEntity<JsonResult>(result, status);
                }
            } else if (role.equals("TEACHER")) {
                Teacher teacher = service3.getTeacherByTid(account);
                if (teacher != null) {
                    pwd = MD5Utils.encode(pwd);
                    if (teacher.getPwd().equals(pwd)) {
                        String token = JWTUtils.createToken(account, teacher.getTname(), role, rememberMe);
                        AccessToken accessToken = new AccessToken(token, "Bearer", role, expiration);
                        teacher.setAuthtoken(token.replace(JWTUtils.TOKEN_PREFIX, ""));
                        teacher.setLoginip(IPUtils.getIpAdr(request));
                        teacher.setLogintime(new Date());
                        teacher.setUpdatetime(new Date());
                        service3.putTeacher(teacher);
                        HttpStatus status = HttpStatus.OK;
                        return new ResponseEntity<AccessToken>(accessToken, status);
                    } else {
                        HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
                        JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, "账号密码错误");
                        return new ResponseEntity<JsonResult>(result, status);
                    }
                } else {
                    HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
                    JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, "不存在的账号：" + account);
                    return new ResponseEntity<JsonResult>(result, status);
                }
            } else {
                HttpStatus status = HttpStatus.UNPROCESSABLE_ENTITY;
                JsonResult result = new JsonResult(ResultStatus.PARAMS_ERROR, "不存在的角色：" + role);
                return new ResponseEntity<JsonResult>(result, status);
            }
        }
    }
}
